def test(fn):
= 1,100
low,high = 9
expected = fn(low,high) # 11, 22, 33, 44, 55, 66, 77, 88, and 99.
symmetric_count assert symmetric_count == expected
= 1200, 1230
low, high = 4
expected = fn(low,high) # 1203, 1212, 1221, and 1230
symmetric_count assert symmetric_count == expected
= 0, 10000
low, high = 624
expected = fn(low,high)
symmetric_count assert symmetric_count == expected
Problem Source: Leetcode
Problem Description
You are given two positive integers low
and high
.
An integer x
consisting of 2 * n
digits is symmetric if the sum of the first n
digits of x
is equal to the sum of the last n
digits of x
. Numbers with an odd number of digits are never symmetric.
Return the number of symmetric integers in the range [low, high]
.
tests
Solution
- Time Complexity:
O(n^2)
- Space Complexity:
O(1)
def sum(arr):
= 0
ttl for a in arr:
+= int(a)
ttl return ttl
def split_int(x):
= len(x)//2
half = x[:half], x[-half:]
left, right return left, right
def isSymmetric(x, ):
= str(x)
x if len(x)%2 == 1: return False
= len(x)//2
half return sum(x[:half]) == sum(x[-half:])
def countSymmetricIntegers(low: int, high: int) -> int:
= 0
symmetric_count for num in range(low, high+1):
+= isSymmetric(num)
symmetric_count return symmetric_count
test(countSymmetricIntegers)
import timeit
lambda: countSymmetricIntegers(0,10000),number=1000) timeit.timeit(
4.902573416009545